package com.study.bigdata.spark.sql

import org.apache.spark.SparkConf
import org.apache.spark.sql._
import org.apache.spark.sql.expressions.Aggregator

object Spark04_SparkSQL_JDBC {
  def main(args: Array[String]): Unit = {
    // TODO 创建SparkSql的运行环境   环境+对象+隐式转换
    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("sparkSQL")
    val spark = SparkSession.builder().config(sparkConf).getOrCreate()
    import spark.implicits._

    //读取MySQL的数据
    val df = spark.read
      .format("jdbc")
      .option("url", "jdbc:mysql://192.168.220.1:3306/mydb")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "root")
      .option("dbtable", "course")
      .load()
    df.show
    /*
    | id|  name|
    +---+------+
    |  1|  java|
    |  2|   php|
    |  3| mysql|
    |  4|hadoop|
    +---+------+
     */
    //保存数据
    df.write
      .format("jdbc")
      .option("url", "jdbc:mysql://192.168.220.1:3306/mydb")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "root")
      .option("dbtable", "course_idea")
      .mode(SaveMode.Append)
      .save()

    // TODO 关闭环境
    spark.close()
  }
}
